<template>
  <div class="wk-location" @mouseenter="hovering = true" @mouseleave="hovering = false">
    <el-input v-model="dataValue.address" :disabled="disabled"
              readonly
              clearable
              placeholder="点击定位"
              @click="inputClick"
              @clear="inputClear">
      <template v-slot:suffix>
        <i v-if="dataValue.address && hovering"
           class="el-icon-circle-close"
           style="cursor: pointer;"
           @click.stop="inputClear"/>
        <i v-else class="wk wk-icon-location"/>
      </template>
    </el-input>

    <WkLocationPointDialog :value="dataValue" v-model:visible="pointDialogVisible" @select="pointSelect"/>
  </div>
</template>

<script setup>
import WkLocationPointDialog from '../WkLocationPointDialog/index.vue'

import {isObject} from '/src/utils/types.js'
// import { valueEquals } from 'element-ui/lib/utils/util'
import {valueEquals} from '/src/utils/elementui.js'
// import Emitter from 'element-ui/lib/mixins/emitter'


defineOptions({ // 定位
  name: 'WkLocation',
})

const props = defineProps({
  // eslint-disable-next-line vue/require-prop-types
  value: {
    required: true
  },
  disabled: Boolean
})

const emits  = defineEmits(['input', 'change'])

const optionData = reactive({
  hovering: false,
  dataValue: getDefaultValue(),
  pointDialogVisible: false
})
const {hovering, dataValue, pointDialogVisible} = toRefs(optionData)

watch(props.value, (val) => {
    if (!valueEquals(val, optionData.dataValue)) {
      if (isObject(props.value)) {
        optionData.dataValue = val
      } else {
        optionData.dataValue = getDefaultValue()
        emits('input', optionData.dataValue)
      }
    }
  },{
  immediate: true
})


function getDefaultValue() {
  return {
    lat: '',
    lng: '',
    address: ''
  }
}

function inputClick() {
  if (!props.disabled) {
    optionData.pointDialogVisible = true
  }
}

function inputClear() {
  optionData.dataValue = getDefaultValue()
  valueChange()
}

function pointSelect(data) {
  if (data) {
    optionData.dataValue = {
      lat: data.point.lat,
      lng: data.point.lng,
      address: data.address + data.title
    }
  }

  valueChange()
}

function valueChange() {
  emits('input', optionData.dataValue)
  emits('change', optionData.dataValue)
  // todo whf 重要，源代码里这里有个dispatch，能不能取消掉
  // .dispatch('ElFormItem', 'el.form.change', optionData.dataValue)
}
</script>



<style lang="scss" scoped>

</style>
